<template>
  <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form ref="contentForm" :rules="rules" :model="content" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
      {{#each fieldList}}
      <el-form-item :label="$t('biz.{{ camelCase ../name }}.{{ camelCase fieldName }}')" prop="{{ camelCase fieldName }}">
        <el-input v-model="content.{{ camelCase fieldName }}"/>
      </el-form-item>
      {{/each}}
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">\{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="saveOrUpdateData()">\{{ $t('table.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {{ camelCase name }}Api from '@/api/biz/{{ name }}'

export default {
  name: '{{ properCase name }}Edit',
  data() {
    return {
      dialogFormVisible: false,
      dialogStatus: '',
      dialogTitleMap: { update: '创建', create: '保存' },
      content: {
        {{#each fieldList}}
        {{ camelCase fieldName }}: '',
        {{/each}}
        id: undefined
      },
      rules: {
        {{#each fieldList}}
        {{ camelCase fieldName }}: [{required: true, message: '{{ camelCase fieldName }} is required', trigger: 'change'}],
        {{/each}}
      }
    }
  },
  created() {
  },
  methods: {
    resetContent() {
      this.content = {
        {{#each fieldList}}
        {{ camelCase fieldName }}: '',
        {{/each}}
        id: undefined
      }
    },
    handleShowEdit(id = undefined) {
      this.resetContent()
      const isCreate = id === undefined || id === null || id === ''
      this.dialogStatus = isCreate ? 'create' : 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['contentForm'].clearValidate()
      })
      if (!isCreate) {
        {{ camelCase name }}Api.get(id).then((reponses) => {
          this.content = reponses.content
        })
      }
    },
    handleDataSuccess() {
      this.dialogFormVisible = false
      this.$emit('success')
    },
    saveOrUpdateData() {
      this.$refs['contentForm'].validate((valid) => {
        if (valid) {
          {{ camelCase name }}Api.saveOrUpdate(this.content).then((reponses) => {
            this.$notify({title: '成功', message: '创建成功', type: 'success', duration: 2000})
            this.handleDataSuccess()
          }).catch(error => {
	          this.dialogFormVisible = true
	          console.info(error)
          })
        }
      })
    }
  }
}
</script>
